package org.darcy.youchat.library.emoji;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.viewpager.widget.ViewPager;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * 表情贴图区
 */
public class EmotionPickerView extends LinearLayout implements IEmoticonCategoryChanged {

    private Context context;

    private IEmotionSelectedListener emotionSelectedListener;

    private boolean loaded = false;

    private boolean withSticker;

    private EmotionView gifView;

    private ViewPager currentEmojiPage;

    private LinearLayout pageNumberLayout;

    private HorizontalScrollView scrollView;

    private LinearLayout tabView;

    private int categoryIndex;

    private Handler uiHandler;

    OnClickListener tabCheckListener;

    public EmotionPickerView(Context context) {
        super(context);
        this.tabCheckListener = v -> EmotionPickerView.this.onEmoticonBtnChecked(v.getId());
        init(context);
    }

    /**
     * 这个构造函数是xml文件初始化使用的
     */
    public EmotionPickerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.tabCheckListener = v -> onEmoticonBtnChecked(v.getId());
        init(context);
    }

    private void init(Context context) {
        this.context = context;
        this.uiHandler = new Handler(context.getMainLooper());
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.nim_emoji_layout, this);
    }

    protected void onFinishInflate() {
        super.onFinishInflate();
        setupEmojiView();
    }

    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
    }

    public void setEmotionSelectedListener(IEmotionSelectedListener listener) {
        if (listener != null) {
            this.emotionSelectedListener = listener;
        } else {
            Log.i("sticker", "listener is null");
        }
    }

    protected void setupEmojiView() {
        this.currentEmojiPage = findViewById(R.id.scrPlugin);
        this.pageNumberLayout = findViewById(R.id.layout_scr_bottom);
        this.tabView = findViewById(R.id.emoj_tab_view);
        this.scrollView = findViewById(R.id.emoj_tab_view_container);
        findViewById(R.id.top_divider_line).setVisibility(View.VISIBLE);
    }

    private void loadStickers() {
        if (!this.withSticker) {
            this.scrollView.setVisibility(View.GONE);
            return;
        }
        StickerManager manager = StickerManager.getInstance();
        this.tabView.removeAllViews();
        int index = 0;
        CheckedImageButton btn = addEmoticonTabBtn(index++, this.tabCheckListener);
        btn.setNormalImageId(R.drawable.nim_emoji_icon_inactive);
        btn.setCheckedImageId(R.drawable.nim_emoji_icon);
        List<StickerCategory> categories = manager.getStickerCategories();
        for (StickerCategory category : categories) {
            btn = addEmoticonTabBtn(index++, this.tabCheckListener);
            setCheckedButtonImage(btn, category);
        }
    }

    private CheckedImageButton addEmoticonTabBtn(int index, OnClickListener listener) {
        CheckedImageButton emotBtn = new CheckedImageButton(this.context);
        emotBtn.setNormalBkResId(R.drawable.nim_sticker_button_background_normal_layer_list);
        emotBtn.setCheckedBkResId(R.drawable.nim_sticker_button_background_pressed_layer_list);
        emotBtn.setId(index);
        emotBtn.setOnClickListener(listener);
        emotBtn.setScaleType(ImageView.ScaleType.FIT_CENTER);
        emotBtn.setPaddingValue(YouChatEmotionKit.dip2px(7.0F));
        int emojiBtnWidth = YouChatEmotionKit.dip2px(50.0F);
        int emojiBtnHeight = YouChatEmotionKit.dip2px(44.0F);
        this.tabView.addView(emotBtn);
        ViewGroup.LayoutParams emojiBtnLayoutParams = emotBtn.getLayoutParams();
        emojiBtnLayoutParams.width = emojiBtnWidth;
        emojiBtnLayoutParams.height = emojiBtnHeight;
        emotBtn.setLayoutParams(emojiBtnLayoutParams);
        return emotBtn;
    }

    private void setCheckedButtonImage(CheckedImageButton btn, StickerCategory category) {
        try {
            InputStream is = category.getCoverNormalInputStream(this.context);
            if (is != null) {
                Bitmap bmp = BitmapDecoder.decode(is);
                btn.setNormalImage(bmp);
                is.close();
            }
            is = category.getCoverPressedInputStream(this.context);
            if (is != null) {
                Bitmap bmp = BitmapDecoder.decode(is);
                btn.setCheckedImage(bmp);
                is.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void onEmoticonBtnChecked(int index) {
        updateTabButton(index);
        showEmotionPager(index);
    }

    private void updateTabButton(int index) {
        for (int i = 0; i < tabView.getChildCount(); i++) {
            View child = tabView.getChildAt(i);
            if (child instanceof FrameLayout)
                child = ((FrameLayout) child).getChildAt(0);
            if (child instanceof CheckedImageButton) {
                CheckedImageButton tabButton = (CheckedImageButton) child;
                if (tabButton.isChecked() && i != index) {
                    tabButton.setChecked(false);
                } else if (!tabButton.isChecked() && i == index) {
                    tabButton.setChecked(true);
                }
            }
        }
    }

    /**
     * 显示表情符
     */
    private void showEmotionPager(int index) {
        if (this.gifView == null) {
            this.gifView = new EmotionView(this.context, this.emotionSelectedListener, this.currentEmojiPage, this.pageNumberLayout);
        }
        this.gifView.showStickers(index);
    }

    private void showEmojiView() {
        if (this.gifView == null)
            this.gifView = new EmotionView(this.context, this.emotionSelectedListener, this.currentEmojiPage, this.pageNumberLayout);
        this.gifView.showEmojis();
    }

    private void show() {
        if (this.emotionSelectedListener == null)
            Log.i("sticker", "show picker view when listener is null");
        if (!this.withSticker) {
            showEmojiView();
        } else {
            onEmoticonBtnChecked(0);
            setSelectedVisible(0);
        }
    }

    private void setSelectedVisible(final int index) {
        Runnable runnable = new Runnable() {
            public void run() {
                if (EmotionPickerView.this.scrollView.getChildAt(0).getWidth() == 0)
                    EmotionPickerView.this.uiHandler.postDelayed(this, 100L);
                int x = -1;
                View child = EmotionPickerView.this.tabView.getChildAt(index);
                if (child != null &&
                        child.getRight() > EmotionPickerView.this.scrollView.getWidth())
                    x = child.getRight() - EmotionPickerView.this.scrollView.getWidth();
                if (x != -1)
                    EmotionPickerView.this.scrollView.smoothScrollTo(x, 0);
            }
        };
        this.uiHandler.postDelayed(runnable, 100L);
    }

    public void onCategoryChanged(int index) {
        if (this.categoryIndex == index)
            return;
        this.categoryIndex = index;
        updateTabButton(index);
    }

    public void show(IEmotionSelectedListener listener) {
        setEmotionSelectedListener(listener);
        if (this.loaded)
            return;
        loadStickers();
        this.loaded = true;
        show();
    }

    public void setWithSticker(boolean withSticker) {
        this.withSticker = withSticker;
    }

    public void attachEditText(EditText messageEditText) {
        if (this.gifView != null)
            this.gifView.attachEditText(messageEditText);
    }
}
